import json
import logging

from django.shortcuts import render
from django.views import View
from utils.json_fun import to_json_data
from utils.res_code import error_map,Code
from .models import Users
from .form import RegisterForm,LoginForm
from django.contrib.auth import login, logout

#导入日志器
logger = logging.getLogger('django')


class CheckRegisterView(View):
    """
    create get page
    """
    def get(self,request):
        """
        handle get request, render register page.
        # 2、创建get方法
        :param request:
        :return:
        """
        return render(request,'users/register.html')

    def post(self,request):
        """
        create post page
        :param request:
        :return:
        """
        # 1. 获取数据
        # 2. 校验数据
        # 3. 将数据存入数据库
        try:
            json_data = request.body
            if not json_data:
                return to_json_data(errno=Code.PARAMERR,errmsg='参数为空,请重新输入')
            dict_data = json.loads(json_data.decode('utf8'))
        except Exception as e:
            logger.info('错误信息:\n{}'.format(e))
            return to_json_data(errno=Code.UNKOWNERR,errmsg=error_map[Code.UNKOWNERR])

        check_form = RegisterForm(data=dict_data)
        if check_form.is_valid():
            username = check_form.cleaned_data.get('username')
            password = check_form.cleaned_data.get('password')
            mobile = check_form.cleaned_data.get('mobile')

            # 6、将用户信息保存到数据库
            user = Users.objects.create_user(username=username, password=password, mobile=mobile)
            # user.mobile = mobile
            # user.save()
            login(request, user)
            return to_json_data(errmsg="恭喜您，注册成功！")
        else:
            # 7、将结果返回给前端
            # 定义一个错误信息列表
            err_msg_list = []
            for item in check_form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
                # print(item[0].get('message'))   # for test
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)


class LoginView(View):
    """
    登录类
    """
    def get(self,request):
        """
            login page
            :param requesrt:
            :return:
            """
        return render(request, 'users/login.html')

    def post(self,request):
        """
        Post page
        :param requesrt:
        :return:
        """
        try:
            json_data = request.body
            if not json_data:
                return to_json_data(errno=Code.PARAMERR,errmsg='参数为空,请重新输入')
            dict_data = json.loads(json_data.decode("utf8"))
        except Exception as e:
            logger.info('错误信息:\n{}'.format(e))
            return to_json_data(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR])

        check_form = LoginForm(data=dict_data,request=request)

        if check_form.is_valid():
            return to_json_data(errmsg="恭喜您，登录成功！")
        else:
            err_msg_list = []
            for item in check_form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
                # print(item[0].get('message'))   # for test
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)









